package com.cdtu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdtu.dto.R;
import com.cdtu.dto.SightsDTO;
import com.cdtu.entity.Sights;
import com.cdtu.entity.Ticket;
import com.cdtu.mapper.TicketMapper;
import com.cdtu.service.SightsService;
import com.cdtu.service.TicketService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : Sakura
 * @Date : 2023/10/28 14:00
 * @Description : TODO 用来接收景点信息的请求
 */
@RestController
@RequestMapping("/api/sights")
//解决跨域问题
@CrossOrigin
public class SightsController {

    @Autowired
    private SightsService sightsService;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private TicketMapper ticketMapper;

    @GetMapping("/list/{pageNo}/{pageSize}")
    public R list(@PathVariable Integer pageNo,
                  @PathVariable Integer pageSize,
                  @RequestParam(required = false) String searchKey) {
        LambdaQueryWrapper<Sights> sightWrapper = new LambdaQueryWrapper<>();
        Page<Sights> page = getUnCheckList(pageNo, pageSize, searchKey, sightWrapper);
//        Page<SightsDTO> pageDTO = new Page<>();
//        page.getRecords().stream().map(item-> {
//            SightsDTO dto = new SightsDTO();
//            BeanUtils.copyProperties(item, dto);
////            半票
//            Ticket ticket = ticketMapper.getPriceBySightId(item.getId(), 0);
//
//
//        }).collect(Collectors.toList());
        return R.success(page);
    }

    @PutMapping("/changeState/{sid}/{state}")
    public R changeState(@PathVariable("sid") long sid,
                         @PathVariable("state") int state) {
        Sights sights = sightsService.getById(sid);
        if (state == 1) {
            sights.setSightStatus(0);
        } else {
            sights.setSightStatus(1);
        }
        boolean update = sightsService.updateById(sights);
        if (!update) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    @Transactional
    @PostMapping("/addOrUpdate")
    public R sightDetail(@RequestBody SightsDTO dto) {
        Sights sight = new Sights();
        BeanUtils.copyProperties(dto, sight);
        if (Objects.isNull(sight.getId()) || sight.getId() == 0) {
//            id为null是添加
//            先添加半票
//            if (dto.getChildPrice() > 0) {
//
//            }
//
//            //            再添加全票
//            if (dto.getChildPrice() > 0) {
//
//            }
            sight.setChecked(0);
            boolean save = sightsService.save(sight);
            if (!save) {
                return R.error("添加失败，请重新尝试");
            }
            return R.success("添加成功");
        }
//        id不为Null就是修改
//        修改的时候半票和全票都要修改
//        if (dto.getChildPrice() > 0) {
////            先修改半票
//        }
//
//        if (dto.getAdultPrice() > 0) {
////            再修改全票
//        }
        sight.setChecked(0);
        boolean update = sightsService.updateById(sight);
        if (!update) {
            return R.error("修改失败，请重新尝试");
        }
        return R.success("修改成功");
    }

    @Transactional
    @PostMapping("/delete/{sid}")
    public R deleteDept(@PathVariable("sid") long sid) {
        //删除景点的同时 要把关联的门票也删除
        LambdaQueryWrapper<Ticket> ticketWrapper = new LambdaQueryWrapper<>();
        ticketWrapper.eq(Ticket::getSightId, sid);
        boolean remove = ticketService.remove(ticketWrapper);

        remove = sightsService.removeById(sid);
        if (!remove) {
            return R.error("删除失败，请重新尝试");
        }
        return R.success("删除成功");
    }

    @GetMapping("/check/list/{pageNo}/{pageSize}")
    public R unCheckList(@PathVariable Integer pageNo,
                         @PathVariable Integer pageSize,
                         @RequestParam(required = false) String searchKey) {
        LambdaQueryWrapper<Sights> sightWrapper = new LambdaQueryWrapper<>();
        //未审核的条例
        sightWrapper.eq(Sights::getChecked, 0);
        Page<Sights> page = getUnCheckList(pageNo, pageSize, searchKey, sightWrapper);
        return R.success(page);
    }

    private Page<Sights> getUnCheckList(Integer pageNo, Integer pageSize, String searchKey, LambdaQueryWrapper<Sights> sightWrapper) {
        sightWrapper.like(searchKey != null && searchKey != "", Sights::getName, searchKey);
        Page<Sights> page = sightsService.page(new Page<>(pageNo, pageSize), sightWrapper);
        return page;
    }

    /**
     * 同意审核改变状态
     *
     * @param sid:
     * @param uid:
     * @return R
     * @author Sakura
     * @date 2023/10/28 18:18
     */
    @PostMapping("/agree/{sid}/{uid}")
    public R agree(@PathVariable("sid") long sid,
                   @PathVariable("uid") Long uid) {
        Sights sights = sightsService.getById(sid);
        sights.setChecked(1);
        sights.setCheckUser(uid);
        boolean update = sightsService.updateById(sights);
        if (!update) {
            return R.error("审核失败，请重新尝试");
        }
        return R.success("审核成功");
    }


    /**
     * 同意审核改变状态
     *
     * @param sid:
     * @param uid:
     * @return R
     * @author Sakura
     * @date 2023/10/28 18:18
     */
    @PostMapping("/refuse/{sid}/{uid}")
    public R refuse(@PathVariable("sid") long sid,
                    @PathVariable("uid") Long uid,
                    @RequestBody String detail) {

        Sights sights = sightsService.getById(sid);
        sights.setChecked(2);
        sights.setCheckUser(uid);
        sights.setRefuseReason(detail);
        boolean update = sightsService.updateById(sights);
        if (!update) {
            return R.error("驳回失败，请重新尝试");
        }
        return R.success("驳回成功");
    }

    /**
     * 同意审核改变状态
     *
     * @return R
     * @author Sakura
     * @date 2023/10/28 18:18
     */
    @GetMapping("/list/select")
    public R selectList() {
        List<Sights> list = sightsService.list();
        return R.success(list);
    }

    /**
     * 游客查看的景区列表
     * @param :
     * @return R
     * @author Sakura
     * @date 2023/10/28 22:44
     */
    @GetMapping("/view/list/{pageNo}/{pageSize}")
    public R viewList(@PathVariable Integer pageNo,
                      @PathVariable Integer pageSize,
                      @RequestParam(required = false) String searchKey) {
        LambdaQueryWrapper<Sights> sightWrapper = new LambdaQueryWrapper<>();
        if (searchKey != null && searchKey != "") {
            sightWrapper.like(Sights::getName, searchKey);
        }
        Page<Sights> page = sightsService.page(new Page<>(pageNo, pageSize), sightWrapper);
        List<Sights> sightsList = page
                .getRecords().stream()
                .filter(item -> item.getChecked() == 1)
                .filter(item->item.getSightStatus()==1).collect(Collectors.toList());
        page.setRecords(sightsList);
        return R.success(page);
    }
}
